package com.haizhi.crm.biz.service.impl;

import com.haizhi.crm.biz.builder.MsgSearchQoBuilder;
import com.haizhi.crm.biz.constant.MessageType;
import com.haizhi.crm.biz.dao.MessageDao;
import com.haizhi.crm.biz.dao.MessageUserDao;
import com.haizhi.crm.biz.dao.UserShareDao;
import com.haizhi.crm.biz.dao.VisitRecordDao;
import com.haizhi.crm.biz.model.MessageDo;
import com.haizhi.crm.biz.model.MessageQo;
import com.haizhi.crm.biz.model.MessageVo;
import com.haizhi.crm.biz.service.MessageService;
import com.haizhi.crm.biz.util.MessageUtil;
import com.haizhi.crm.common.constant.CrmSchema;
import com.haizhi.crm.search.model.SearchQo;
import com.haizhi.crm.search.model.SearchVo;
import com.haizhi.crm.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * Created by wangshan on 2018/5/16.
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageDao messageDao;

    @Autowired
    private MessageUserDao messageUserDao;

    @Autowired
    private SearchService searchService;

    @Autowired
    private UserShareDao userShareDao;

    @Autowired
    private VisitRecordDao visitRecordDao;

//    public List<MessageVo> query()


    @Override
    public MessageDo add(MessageDo messageDo) {
        return messageDao.save(messageDo);
    }

    @Override
    public void addList(List<MessageDo> messageDoList) {
        for (MessageDo messageDo : messageDoList) {
            messageDao.save(messageDo);
        }
    }

    @Override
    public List<MessageVo> query(MessageQo messageQo) {

        return null;
    }

    @Override
    public Object detail(Long messageId) {
        MessageDo messageDo = messageDao.findById(messageId);
        SearchQo searchQo = MsgSearchQoBuilder.get(CrmSchema.CRM, messageDo.getMsgSchema(), messageDo.getMsgKey());
        SearchVo searchVo = searchService.search(searchQo);
        List<Map<String, String>> datas = MessageUtil.toList(searchVo.getSearchResp().getData());
        if (datas.size() == 0) {
            return null;
        }
        Map<String, String> data = datas.get(0);
        return data;
    }

    @Override
    public Object detailActual(Long messageId) {
        MessageDo messageDo = messageDao.findById(messageId);
        if (MessageType.SHARE.equals(messageDo.getMsgSchema())) {
            return userShareDao.findById(Long.parseLong(messageDo.getMsgKey()));
        } else if (MessageType.VISIT.equals(messageDo.getMsgSchema())) {
            return visitRecordDao.findById(Long.parseLong(messageDo.getMsgKey()));
        } else {
            return null;
        }
    }
}
